package com.jule.chat.network.protocol;

import com.google.protobuf.MessageLite;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.http.websocketx.BinaryWebSocketFrame;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Created by xujian on 2017/5/16 0016.
 */
public class Response implements Cloneable {

    private final static Logger logger = LoggerFactory.getLogger(Response.class);
    protected int functionId;
    protected MessageLite messageLite;

    public void send(final ChannelHandlerContext channelHandlerContext) {
        try {
            ByteBuf byteBuf = channelHandlerContext.alloc().buffer(1024);
            byte[] playLoad = messageLite.toByteArray();
            byteBuf.writeInt(12 + playLoad.length);
            byteBuf.writeInt(functionId);
            byteBuf.writeInt(0);
            byteBuf.writeInt(0);
            byteBuf.writeBytes(playLoad);
            BinaryWebSocketFrame binaryWebSocketFrame = new BinaryWebSocketFrame(byteBuf);
            channelHandlerContext.writeAndFlush(binaryWebSocketFrame);
        } catch (Exception e) {
        }

        if (messageLite != null) {
            logger.debug("发送数据 " + functionId + " ->" + messageLite.toString());
        }
    }

    /**
     * @param messageLite
     */
    public void setMessageLite(MessageLite messageLite) {
        this.messageLite = messageLite;
    }

    /**
     * @param functionId
     */
    public Response(int functionId) {
        this.functionId = functionId;
    }

    /**
     * @return
     */
    public Response clone() {
        try {
            return (Response) super.clone();
        } catch (CloneNotSupportedException e) {
            return null;
        }
    }
}
